<!--
* description: 备件价格新增
* author: xuliwen
* createdDate: 2021-01-21
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :highlight-current-row="false"
      :dynamic-is-show-more-btn="true"
      :dynamic-api-style="'restful'"
      :dynamic-cell-style="columnStyle"
      :callback-obj="callbackObj"
      :page-size-array="[50, 100, 200, 400]"
      :dynamic-page-size="50"
      :custom-handle-page-and-size-change="handlePageAndSizeChange"
    >
      <template #costPrice="{row}">
        <span> {{ row.costPrice | fixTwo }}</span>
      </template>

      <template #pointPriceNotTax="{row}">
        <span> {{ row.pointPriceNotTax | fixTwo }}</span>
      </template>

      <template #urgentOrderPriceNotTax="{row}">
        <el-input v-model="row.urgentOrderPriceNotTax" clearable placeholder="紧急订单价"></el-input>
      </template>
      <!--      订单利润率-->
      <template #outletProfitMargin="scope">
        <el-input
          v-model="scope.row['outletProfitMargin']"
          placeholder="订单利润率"
          @change="profitChange($event, scope.row, scope.col)"
        >
          <template slot="append">%</template>
        </el-input>
      </template>
      <!-- 建议零售价-->
      <template #userPrice="scope">
        <el-input
          v-model="scope.row['userPrice']"
          placeholder="建议零售价"
          clearable
          @change="userPriceChange($event, scope.row, scope.col)"
        >
          <template #append>￥</template>
        </el-input>
      </template>
      <!--      总部利润率 -->
      <template #headquartersProfitMargin="scope">
        <span
          v-show="scope.row['headquartersProfitMargin'] !== null && scope.row['headquartersProfitMargin']"
        >
          {{ scope.row['headquartersProfitMargin'] | percentage }}
        </span>
      </template>
      <!--      紧急订单浮动率调整-->
      <template #customArea>
        <div style="display: flex;width: 300px">
          <el-popover
            style="padding-left: 10px"
            placement="right"
            width="300"
            trigger="click"
          >
            <el-input
              v-model="jjrate"
              placeholder="请输入紧急订单浮动率"
              clearable
              @change="jjrateChange"
            >
              <el-button slot="append" icon="el-icon-circle-check" @click="saveRate">保存</el-button>
            </el-input>
            <el-button slot="reference">紧急订单浮动率： {{ jjrate }} %</el-button>
          </el-popover>
        </div>
      </template>
    </one-table-template>

    <!-- <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible="editPopupsVisible"
      :popups-state="editPopupsState"
      :dynamic-api-style="'restful'"
      @close="close"
    /> -->
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import { exportExcel } from '@/utils/getTimeString.js'
import api from '@/api/pa/apiBaseData'
import { orgApis } from '@/api/pabasicdataapi'
import Vue from 'vue'

export default {
  name: 'PricePartsAdd',

  components: {
    OneTableTemplate
    // Edit: () => import("./edit"),
  },
  filters: {
    // 小数转换百分比显示
    percentage: function(num) {
      if (!num) return ''
      return (Number(num) * 100).toFixed(2) + '%'
    },
    fixTwo: function(val) {
      return Number(val).toFixed(2)
    }
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next((vm) => {
        // 请求最新的浮动率
        vm.loadDatas()
        // 查询
        vm.queryTableS(1)
      })
    })
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      // 订单浮动率
      jjrate: 0,
      handlePageAndSizeChange: {
        handleSizeChange: val => {
          this.queryTableS()
        },
        handleCurrentChange: val => {
          this.queryTableS()
        }
      },
      icon: 'el-icon-arrow-down',
      status: false,
      editRowData: {},
      selectiondata: [],

      datas: {},
      // 网格查询API配置对象
      apiConfig: api.queryAddSparePartPriceList,
      callbackObj: {
        // 手动勾选时
        // onCheckSelect: (selection, row) => {
        //   this.selectiondata = selection
        // },
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectiondata = selection
          this.onCheckSelectChange1(selection)
        }
      },
      columnStyle({ row, column, rowIndex, columnIndex }) {
        if (!row['headquartersProfitMargin']) return ''
        // 颜色 红 -- 黄 -- 绿
        const bg = {
          red: 'background:#eb4d4b !important',
          yellow: 'background:#f9ca24 !important',
          green: 'background:#badc58 !important'
        }
        // 低于最低阈值时，标红；不在区间内，但高于最低阈值，标黄；
        function handleProfit({ range: [low, high], min }, value, prop) {
          if (value < min) {
            return bg.red
          } else if (value > min && value < low) {
            return bg.yellow
          } else if (value >= low && value <= high) {
            return bg.green
          } else {
            return bg.yellow
          }
        }
        // dlrProfitMarginH  dlrProfitMarginL  网点利润率区间
        // oemProfitMarginH  oemProfitMarginL  总部利润率区间
        // dlrProfitMarginMin 网点最低利润率
        // oemProfitMarginMin 总部最低利润率
        if (column.property === 'headquartersProfitMargin') {
          return handleProfit({
            range: [row['oemProfitMarginL'], row['oemProfitMarginH']],
            min: row['oemProfitMarginMin']
          }, Number(row['headquartersProfitMargin']), 'headquartersProfitMargin'
          )
        }
      },
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTableS(),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        // {
        //   compKey: 'btnKey3',
        //   type: '',
        //   size: 'small',
        //   name: 'add',
        //   clickEvent: this.add,
        //   text: this.$t('sys.button.add'), // 新增
        //   position: 'left'
        // },
        // {
        //   compKey: "btnKey3",
        //   type: "",
        //   size: "small",
        //   disabled: true,
        //   parentFileds: "disabled:table",
        //   clickEvent: () => this.pass("priceTrial"),
        //   text: "价格试算", // 新增
        //   name: "batchSubmit",
        //   position: "left",
        // },
        {
          compKey: 'btnKey4',
          type: '',
          size: 'small',
          disabled: true,
          parentFileds: 'disabled:table',
          clickEvent: () => this.pass('save'),
          text: '保存',
          name: 'adopt',
          position: 'left'
        },
        {
          compKey: 'btnKey4',
          type: '',
          size: 'small',
          disabled: true,
          parentFileds: 'disabled:table',
          clickEvent: () => this.pass('submit'),
          text: '提交', // 新增
          name: 'adopt',
          position: 'left'
        },
        {
          compKey: 'btnKey5',
          disabled: true,
          parentFileds: 'disabled:table',
          type: '',
          size: 'small',
          clickEvent: () => this.pass('delet'),
          text: '删除', // err
          name: 'reject',
          position: 'left'
        },
        {
          compKey: 'comKey2',
          type: '',
          size: 'small',
          name: 'importTemplate',
          position: 'upload',
          clickEvent: () => this.handFileListChange(),
          text: '导入',
          disabled: false
        },
        {
          compKey: 'comKey11',
          type: 'text',
          size: 'small',
          name: '',
          position: 'upload',
          click: (event) => {
            this.templateDownload()
            // this.export(
            //   // api.templateDownload.APIUrl,
            //   '欠拨结案特殊备件定义模板',
            //   { dataType: 'excel' }
            // )
          }
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          clickEvent: () => this.exportExcel111(),
          text: '导出',
          name: 'export',
          position: 'left'
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey6',
              labelName: '备件编码：',
              codeField: 'partNo',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey7',
              labelName: '备件名称：',
              codeField: 'partName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey1',
              labelName: '维修类型：',
              codeField: 'partRepairType',
              textField: 'partRepairTypeName',
              customObj: {
                api: api.queryPartRepairs
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '备件名称码：',
              codeField: 'partNameId',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '备件状态：',
              codeField: 'partStatus',
              customObj: {
                api: api.queryPartStatus
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey4',
              labelName: '供应商：',
              codeField: 'supplierCode',
              textField: 'supplierShortName',
              component: () => import('@/components/ve/multipleSearchInput'),
              type: 'inputText',
              isMust: false,
              dataToObject: {
                // 控制弹窗页面 搜索 网格 元素
                tableComponents: [
                  {
                    compKey: 'compKey1',
                    labelName: '供应商编码：',
                    codeField: 'supplierCode',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey2',
                    labelName: '供应商简称：',
                    codeField: 'supplierShortName',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey3',
                    labelName: '状态：',
                    codeField: 'isEnable',
                    component: () => import('@/components/org/LookupValue'),
                    oFields: 'statusId,statusText',
                    options: [
                      { statusId: '1', statusText: '启用' },
                      { statusId: '0', statusText: '禁用' }
                    ],
                    type: 'dropdownList',
                    isMust: true,
                    span: 8
                  }
                ],
                tableCols: [
                  {
                    prop: 'supplierCode',
                    label: '供应商编码'
                  },
                  {
                    prop: 'supplierShortName',
                    label: '供应商简称'
                  },
                  {
                    prop: 'supplierFullName',
                    label: '供应商全称'
                  },
                  {
                    prop: 'supplierAddr',
                    label: '详细地址'
                  },
                  {
                    prop: 'linkMan',
                    label: '联系人'
                  },
                  {
                    prop: 'linkManTel',
                    label: '联系电话'
                  },
                  {
                    prop: 'isEnableCn',
                    label: '状态'
                  },
                  {
                    prop: 'remark',
                    label: '备注'
                  }
                ],
                formField: {
                  supplierCode: '',
                  isEnable: '',
                  supplierShortName: ''
                },
                returnField: {
                  prop: 'supplierCode',
                  label: '供应商编码'
                },
                api: orgApis.supplierInformationQueryquery
              },
              span: 6
            },
            {
              compKey: 'compKey8',
              labelName: '适用车型：',
              codeField: 'carConfigCn',
              component: () => import('./carName/index'),
              width: '150px',
              type: 'inputText',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey9',
              labelName: '有替代件',
              codeField: 'replacePiece',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '1', statusText: '是' },
                { statusId: '0', statusText: '否' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey10',
              labelName: '审核状态',
              codeField: 'reviewStatus',
              customObj: {
                api: api.queryPartPriceAuditType
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMul: false,
              isMust: false
            }
            // {
            //   compKey: "compKey11",
            //   span: 18,
            //   codeField: "orderStatus",
            //   isMul: true,
            //   component: () =>
            //     import("@/components/org/checkBox/pa_checkGroup.vue"),
            //   type: "",
            //   isMust: false,
            // },
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'partId',
              label: '备件ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partPriceId',
              label: '备件价格ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partPriceReviewId',
              label: '备件价格审核ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'reviewStatus',
              label: '审核状态',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'isEnable',
              label: '是否启用',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partNo',
              label: '备件编码',
              isComponent: true
              // comps: [
              //   {
              //     compKey: "propKey1",
              //     codeField: "partNo",
              //     component: () => import("@/components/org/linkButton"),
              //     clickEvent: (index) => this.edit(index),
              //   },
              // ],
            },
            {
              prop: 'partName',
              label: '备件名称'
            },

            {
              prop: 'purchasePrice',
              label: '采购价',
              hidden: true
            },
            {
              prop: 'costPrice',
              label: '标准成本价',
              isSlot: true
            },
            {
              prop: 'pointPriceNotTax',
              label: '正常订单价',
              width: 120,
              isSlot: true
            },
            {
              prop: 'urgentOrderPriceNotTax',
              label: '紧急订单价',
              width: 150,
              isSlot: true
            },
            {
              prop: 'userPrice',
              label: '建议零售价',
              isSlot: true,
              width: 200
            },
            {
              prop: 'headquartersProfitMargin',
              label: '总部利润率',
              isSlot: true,
              width: 130,
            },
            {
              prop: 'outletProfitMargin',
              label: '正常订单利润率',
              isSlot: true,
              width: 200
            },
            {
              prop: 'pointPriceTax',
              label: '正常订单价含税',
              width: 110,
              hidden: true
            },

            {
              prop: 'partRepairTypeName',
              label: '维修类型'
            },
            {
              prop: 'partNameId',
              label: '备件名称码'
            },
            {
              prop: 'carConfigIdList',
              label: '适用车型'
            },
            {
              prop: 'partStatusCn',
              label: '备件状态'
            },
            {
              prop: 'reviewStatusName',
              label: '审核状态'
            },
            {
              prop: 'remark',
              label: '审核意见'
            }
          ],
      // 表单查询数据
      formField: this.$utils.getFormField(
        this,
        {
          partRepairType: '',
          partNameCn: '',
          partNameId: '',
          partStatus: '',
          supplierCode: '',
          partNo: '',
          partName: '',
          carConfigIdList: '',
          carConfigCn: '',
          replacePiece: '',
          reviewStatus: ''
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      )
    }
  },
  watch: {
    'formField.carConfigCn': {
      deep: true,
      handler: function(newV, oldV) {
        if (newV == '' || newV == null) {
          this.formField.carConfigIdList = ''
        }
      }
    }
  },
  created() {
    // this.$requestAPI({
    //   method: 'get',
    //   apiUrl: api.serviceSysParaValue.APIUrl
    //
    // }).then((res) => {
    //   if (res.result == '1') {
    //     this.datas = res.rows[1]
    //   }
    // })
  },
  mounted() {
    // 列表查询
    this.queryTable(1,'', null, '', response => {
      const rows = response.rows
      rows.forEach(row => {
        row['outletProfitMargin'] = (row['outletProfitMargin'] * 100).toFixed(4)
      })
      this.$refs['multipleTable'].list = rows
    })
    this.loadDatas()
  },

  methods: {
    // 浮动率保存
    reqSaveRate() {
      this.$requestAPI({
        apiUrl: 'mp/e3sh/spareparts/TariffAdjustService/editUrgentOrderFloatingRate.do',
        variables: { UrgentOrderFloatingRate: (Number(this.jjrate) / 100).toFixed(2) }
      }).then(res => {
        if (res.result !== '1') return this.$message(res.msg || '紧急浮动率保存失败！')
        this.$message(res.msg || '紧急浮动率保存成功！')
      }).catch()
    },
    saveRate() {
      const reg = /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/
      if (!reg.test(this.jjrate)) return this.$message('请输入正确的浮动率!')
      // 根据当前浮动率 重新计算每一行
      this.$refs['multipleTable'].list.forEach(row => {
        if (row['outletProfitMargin'] && row['userPrice']) {
          this.calcitems(row)
        }
      })
      this.reqSaveRate()
    },
    jjrateChange(val) {
    },
    async loadDatas() {
      // 列表查询
      let response
      const apiUrl = api.serviceSysParaValue.APIUrl
      const variables = {}
      try {
        response = await this.$requestAPI({ apiUrl, variables, method: 'GET' })
      } catch (e) {
        return false
      }
      if (response.result !== '1') {
        return this.$message(response.msg ? response['msg'] : '请求失败!')
      }
      this.datas = response.rows[1]
      this.jjrate = (Math.round(Number(response.rows[0].ATTRIBUTE1) * 10000)) / 100
    },
    // 未来用户价 发生变化
    userPriceChange(UserPrice, row, col) {
      // console.log(prUserPrice, row, col)
      const panter = /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?)$/
      if (!panter.test(UserPrice)) {
        row[col['prop']] = ''
        if (UserPrice) return this.$message('请输入正确的价格！')
      }
      if (!row['outletProfitMargin'] || !UserPrice) return
      this.calcitems(row, col)
    },
    // 网点利润率 变化事件
    profitChange(profit, row, col) {
      // console.log(profit, row, col)
      // const panter = /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/
      const panter = /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,4}|0\.\d{1,4}?|0)$/
      if (!panter.test(profit)) {
        row[col['prop']] = ''
        if (profit) this.$message('请输入正确的利润率！')
      }
      if (!row['userPrice'] || !profit) return
      this.calcitems(row, col)
    },
    // 计算
    calcitems(row, col) {
      /*
      计算规则:
       1、建议零售价 = 业务维护;
       2、正常订单价利润率 = 业务维护;
       3、正常订单价含税 = 建议零售价 * (1 - 正常订单价利润率);
       4、正常订单价不含税 = 正常订单价含税 / (1 + 税率);
       5、紧急订单价含税 = 建议零售价 * (1 - 正常订单价利润率 + 紧急订单浮动率);
       6、紧急订单价不含税 = 紧急订单价含税 / (1 + 税率);
       7、总部利润率 = 1 - (成本价 / 正常订单价不含税);
      紧急浮动率  urgentOrderFloatingRate

      利润率计算
      总部利润率 = (含税网点价 - 成本价) / 含税网点价
      网点利润率 = (用户价 - 含税网点价) / 用户价
       */
      // 税率
      const serviceSysParaValue = Number(this.datas.serviceSysParaValue)
      // 紧急浮动率
      const urgentOrderFloatingRate = Number(this.jjrate) / 100 || Number(row['urgentOrderFloatingRate'])
      // 用户价
      const userPrice = Number(row['userPrice'])
      // 用户网点利润率
      const outletProfitMargin = Number(row['outletProfitMargin']) / 100
      // 成本价
      const costPrice = Number(row['costPrice'])
      // 正常订单价 （含税）
      const pointPriceTax = userPrice - userPrice * outletProfitMargin
      // debugger
      // 正常订单价 (不含税）
      const pointPriceNotTax = pointPriceTax / (1 + serviceSysParaValue)
      // 未来紧急订单价 (含税)
      const urgentOrderPrice = userPrice * (1 - outletProfitMargin + urgentOrderFloatingRate)
      // 未来紧急订单价 (不含税）
      const urgentOrderPriceNotTax = urgentOrderPrice / (1 + serviceSysParaValue)
      // 未来总部利润率
      const headquartersProfitMargin = 1 - (costPrice / pointPriceNotTax)
      // 赋值
      row['pointPriceTax'] = pointPriceTax.toFixed(2)
      row['pointPriceNotTax'] = pointPriceNotTax.toFixed(2)
      row['headquartersProfitMargin'] = headquartersProfitMargin.toFixed(4)
      row['urgentOrderPrice'] = urgentOrderPrice.toFixed(2)
      row['urgentOrderPriceNotTax'] = urgentOrderPriceNotTax.toFixed(2)
      row['pointPriceNotTax'] = pointPriceNotTax.toFixed(2)
    },
    // changeRow(val, comType, row) {
    //   row.pointPriceNotTax = (Number(row.pointPriceTax) / (1 + Number(this.datas.serviceSysParaValue))).toFixed(2)
    //   row.headquartersProfitMargin = ((1 - Number(row.costPrice / row.pointPriceTax)) * 100).toFixed(2) + '%'
    //   row.outletProfitMargin = ((1 - Number(row.pointPriceTax / row.userPrice)) * 100).toFixed(2) + '%'
    // },
    exportExcel111() {
      exportExcel(
        this.formField,
        api.queryAddSparePartPriceExport.APIUrl,
        api.queryAddSparePartPriceExport.ServiceCode,
        '备件价格新增'
      )
    },
    templateDownload() {
      const fileName = this.$utils.fileNameWithTime('备件价格新增模板.xlsx')
      this.$requestAPI({
        apiUrl: api.queryAddSparePartPriceTemplate.APIUrl,
        variables: { dataType: 'excel' }
      })
        .then((res) => {
          this.$utils.downloadFile(res, fileName)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file)
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType != 'xls' && fileType != 'xlsx') {
        this.$message({
          message: '只能导入后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: '导入中...',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      const that = this
      const url = api.queryAddSparePartPriceimportExcel.APIUrl
      that
        .$requestUpload(url, param)
        .then((response) => {
          if (response.result === '1') {
            this.$message({
              message: '导入成功',
              type: 'success'
            })
            that.queryTableS()
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
        .catch((err) => {})
        .finally(() => {
          loading.close()
        })
    },
    queryTableS() {
      this.queryTable(undefined, '', undefined, '', response => {
        const rows = response.rows
        rows.forEach(row => {
          if (!row['outletProfitMargin'] || !row['urgentOrderPriceNotTax']) return
          row['outletProfitMargin'] = (row['outletProfitMargin'] * 100).toFixed(4)
          row['urgentOrderPriceNotTax'] = row['urgentOrderPriceNotTax'].toFixed(2)
          row['userPrice'] = row['userPrice'].toFixed(2)
        })
        this.$nextTick(() => {
          this.$refs['multipleTable'].list = rows
        })
      })
    },
    pass(type) {
      console.log(1111111111111111)
      console.log(this.selectiondata)
      this.$refs.multipleTable.listLoading = true
      const that = this
      var apiComom
      var params
      var p = this.$utils.deepCopy(this.selectiondata)
      p.forEach(row => {
        // row['outletProfitMargin'] = (Number(row['outletProfitMargin']) / 100).toFixed(4)
        row['outletProfitMargin'] = (Number(row['outletProfitMargin']) / 100).toFixed(6)
      })
      if (type === 'save') {
        apiComom = api.queryAddSparePartPriceSave
        params = p
      } else if (type === 'submit') {
        apiComom = api.queryAddSparePartPriceSubmit
        params = p
      } else if (type === 'delet') {
        apiComom = api.queryAddSparePartPriceDelete
        params = { paramList: p }
      } else if (type === 'priceTrial') {
        apiComom = api.priceCalculation
        params = p
      }
      const queryObj = {
        // api配置
        apiConfig: apiComom,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: params
      }
      // 转换了中台请求格式数据
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then((response) => {
        this.$refs.multipleTable.listLoading = false
        if (response.result === '1') {
          this.$message({
            message: response.msg,
            type: 'success'
          })
          this.queryTableS()
        } else {
          this.$message({
            message: response.msg,
            type: 'warning'
          })
        }
      })
    },
    onCheckSelectChange1(selection) {
      var btn3 = this.tableButtons[2]
      var btn1 = this.tableButtons[3]
      var btn2 = this.tableButtons[4]
      const isCheck = selection && selection.length > 0
      btn1.disabled = !isCheck
      btn2.disabled = !isCheck
      btn3.disabled = !isCheck
    },
    // 编辑获取数据
    edit(index) {
      this.editPopupsState = 'edit'
      this.editPopupsVisible = true
      this.editRowData = this.$utils.deepCopy(
        this.$refs['multipleTable'].list[index]
      )
    }
  }
}
</script>
<style lang='scss' scoped>
</style>
